/*数据库操作*/
// mongod --dbpath "d:\mongodb"
// 宏碁笔记本 mongod --dbpath=C:\mongodbData\
var mongoose = require('mongoose');
var Rx = require('rxjs');
var operators = require("rxjs/operators");
var SERVER_CONST = require("../server-const");
//var utils = require('../server-util/util');
let envConfig = require("../config." + process.env.NODE_ENV + ".js");
mongoose.connect(envConfig.mongodbAddress, {
	useNewUrlParser: true,
});
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
	console.log("/** mongodb connected! **/");
});
//建立模型
/****************************
 * teams
 ****************************/

var teamsProps = {
	DisplayName: String,
	Name: String,
	UpdateAt: String,
	DeleteAt: String,
	Description: String,
	Email: String,
	Type: String,
	CompanyName: String,
	AllowedDomains: String,
	InviteId: String,
	AllowOpenInvite: String,
	LastTeamIconUpdate: String,
	SchemeId: mongoose.Schema.ObjectId,
}
var teamsSchema = new mongoose.Schema(teamsProps);
/****************************
 * teamMembers
 * `TeamId` varchar(26) NOT NULL,
 * `UserId` varchar(26) NOT NULL,
 * `Roles` varchar(64) DEFAULT NULL,
 * `DeleteAt` bigint(20) DEFAULT NULL,
 ****************************/
var teammembersProps = {
	TeamId: mongoose.Schema.ObjectId,
	UserId: mongoose.Schema.ObjectId,
	Roles: String,
	DeleteAt: String,
	SchemeUser: String,
	SchemeAdmin: String,
}
var teammembersSchema = new mongoose.Schema(teammembersProps);
/****************************
 * channels
 * `Id` varchar(26) NOT NULL,
 * `CreateAt` bigint(20) DEFAULT NULL,
 * `UpdateAt` bigint(20) DEFAULT NULL,
 * `DeleteAt` bigint(20) DEFAULT NULL,
 * `TeamId` varchar(26) DEFAULT NULL,
 * `Type` varchar(1) DEFAULT NULL,
 * `DisplayName` varchar(64) DEFAULT NULL,
 * `Name` varchar(64) DEFAULT NULL,
 * `Header` text,
 * `Purpose` varchar(250) DEFAULT NULL,
 * `LastPostAt` bigint(20) DEFAULT NULL,
 * `TotalMsgCount` bigint(20) DEFAULT NULL,
 * `ExtraUpdateAt` bigint(20) DEFAULT NULL,
 * `CreatorId` varchar(26) DEFAULT NULL,
 ****************************/
var channelsProps = {
	CreateAt: String,
	UpdateAt: String,
	DeleteAt: String,
	TeamId: mongoose.Schema.ObjectId,
	Type: String, //private 私聊 //privateGroup 私有群聊 //publicGroup 公开群聊
	DisplayName: String,
	Name: String,
	Header: String,
	Purpose: String,
	LastPostAt: String,
	TotalMsgCount: String,
	ExtraUpdateAt: String,
	CreatorId: mongoose.Schema.ObjectId,
	SchemeId: mongoose.Schema.ObjectId,
}
var channelsSchema = new mongoose.Schema(channelsProps);
/****************************
 * user
 * `Id` varchar(26) NOT NULL,
 * `CreateAt` bigint(20) DEFAULT NULL,
 * `UpdateAt` bigint(20) DEFAULT NULL,
 * `DeleteAt` bigint(20) DEFAULT NULL,
 * `Username` varchar(64) DEFAULT NULL,
 * `Password` varchar(128) DEFAULT NULL,
 * `AuthData` varchar(128) DEFAULT NULL,
 * `AuthService` varchar(32) DEFAULT NULL,
 * `Email` varchar(128) DEFAULT NULL,
 * `EmailVerified` tinyint(1) DEFAULT NULL,
 * `Nickname` varchar(64) DEFAULT NULL,
 * `FirstName` varchar(64) DEFAULT NULL,
 * `LastName` varchar(64) DEFAULT NULL,
 * `Position` varchar(128) DEFAULT NULL,
 * `Roles` text,
 * `AllowMarketing` tinyint(1) DEFAULT NULL,
 * `Props` text,
 * `NotifyProps` text,
 * `LastPasswordUpdate` bigint(20) DEFAULT NULL,
 * `LastPictureUpdate` bigint(20) DEFAULT NULL,
 * `FailedAttempts` int(11) DEFAULT NULL,
 * `Locale` varchar(5) DEFAULT NULL,
 * `MfaActive` tinyint(1) DEFAULT NULL,
 * `MfaSecret` varchar(128) DEFAULT NULL,
 ****************************/
var userProps = {
	Email: String,
	Password: String,
	Username: String,
	Prefix: String,
	Phone: String,
	Agreement: Boolean,
	CreateAt: String,
	UpdateAt: String,
	DeleteAt: String,
	AuthData: String,
	AuthService: String,
	EmailVerified: String,
	Nickname: String,
	FirstName: String,
	LastName: String,
	Position: String,
	Roles: String,
	AllowMarketing: String,
	Props: String,
	NotifyProps: String,
	LastPasswordUpdate: String,
	LastPictureUpdate: String,
	FailedAttempts: String,
	Locale: String,
	MfaActive: String,
	MfaSecret: String
}
var userSchema = new mongoose.Schema(userProps);
/****************************
 * channelMembers
 * `ChannelId` varchar(26) NOT NULL,
 * `UserId` varchar(26) NOT NULL,
 * `Roles` varchar(64) DEFAULT NULL,
 * `LastViewedAt` bigint(20) DEFAULT NULL,
 * `MsgCount` bigint(20) DEFAULT NULL,
 * `MentionCount` bigint(20) DEFAULT NULL,
 * `NotifyProps` text,
 * `LastUpdateAt` bigint(20) DEFAULT NULL,
 ****************************/
var channelMembersProps = {
	ChannelId: mongoose.Schema.ObjectId,
	UserId: mongoose.Schema.ObjectId,
	Roles: String,
	LastViewedAt: String,
	MsgCount: {
		type: Number,
		default: 0
	},
	MentionCount: {
		type: Number,
		default: 0
	},
	//at消息未读数量
	AtMentionCount: {
		type: Number,
		default: 0
	},
	NotifyProps: String,
	LastUpdateAt: String,
	SchemeUser: String,
	SchemeAdmin: String,
}
var channelMembersSchema = new mongoose.Schema(channelMembersProps);
/****************************
 * post
 * `CreateAt` bigint(20) DEFAULT NULL,
 * `UpdateAt` bigint(20) DEFAULT NULL,
 * `EditAt` bigint(20) DEFAULT NULL,
 * `DeleteAt` bigint(20) DEFAULT NULL,
 * `IsPinned` tinyint(1) DEFAULT NULL,
 * `UserId` varchar(26) DEFAULT NULL,
 * `ChannelId` varchar(26) DEFAULT NULL,
 * `RootId` varchar(26) DEFAULT NULL,
 * `ParentId` varchar(26) DEFAULT NULL,
 * `OriginalId` varchar(26) DEFAULT NULL,
 * `Message` text,
 * `Type` varchar(26) DEFAULT NULL,
 * `Props` text,
 * `Hashtags` text,
 * `Filenames` text,
 * `FileIds` varchar(150) DEFAULT NULL,
 * `HasReactions` tinyint(1) DEFAULT NULL,
 ****************************/
var postsProps = {
	CreateAt: String,
	UpdateAt: String,
	EditAt: String,
	DeleteAt: String,
	IsPinned: String,
	UserId: mongoose.Schema.ObjectId,
	ChannelId: mongoose.Schema.ObjectId,
	RootId: mongoose.Schema.ObjectId,
	ParentId: mongoose.Schema.ObjectId,
	OriginalId: mongoose.Schema.ObjectId,
	Message: String,
	/**********************
	 * str : 普通文字
	 * emoji : 表情
	 * CustomEmoji : 自定义表情
	 * img : 图片
	 * file : 文件
	 * code : 代码
	 * url : 链接
	 *********************/
	Type: String,
	FileType: String,
	FileSize: {
		type: Number,
		default: 0
	},
	Props: String,
	FileDisplayName: String,
	PreviewPath: String,
	Hashtags: String,
	Filenames: String,
	FileIds: mongoose.Schema.ObjectId,
	HasReactions: String,
	//at 谁 列表 [{_id,Username,isRead,ChannelId}] isRead = 0 未读 1 已读
	AtWhoList: Array,
	//附加内容
	/*
	1 . type object : MsgQuote 引用 将整条引用消息丢进去,整个消息存进去
	2 . type object[] : MsgEmoji 点赞或者添加表情
						[
							{
								"emoji" : 表情字串
								"names" : 表情名称
								"tags" : [],
								"description" : 表情描述
								"category" : 表情分类
								"Creator" : 创建者
								"CreateAt" : 创建时间
							}
						]
	3 . type [] : MsgCollection 消息收藏 注意这个收藏消息，是给收藏的人看的，不是给所有人看的。在收藏的人面前显示星星
					   [
						   {
								userId:收藏人的id
								userName:收藏人的名字
																collectionArr:收藏标签的数组
						   }
						]
	*/
	Additional: Object,


}
var postSchema = new mongoose.Schema(postsProps);
/****************************
 * file
 * `Id` varchar(26) NOT NULL,
 * `CreatorId` varchar(26) DEFAULT NULL,
 * `PostId` varchar(26) DEFAULT NULL,
 * `CreateAt` bigint(20) DEFAULT NULL,
 * `UpdateAt` bigint(20) DEFAULT NULL,
 * `DeleteAt` bigint(20) DEFAULT NULL,
 * `Path` text,
 * `ThumbnailPath` text,
 * `PreviewPath` text,
 * `Name` text,
 * `Extension` varchar(64) DEFAULT NULL,
 * `Size` bigint(20) DEFAULT NULL,
 * `MimeType` text,
 * `Width` int(11) DEFAULT NULL,
 * `Height` int(11) DEFAULT NULL,
 * `HasPreviewImage` tinyint(1) DEFAULT NULL,
 ****************************/
var filesProps = {
	/**********************
	 * CustomEmoji : 表情
	 * img : 图片
	 * file : 文件
	 * avatar : 头像
	 *********************/
	PostFileType: String,
	FileType: String,
	CreateAt: String,
	UpdateAt: String,
	EditAt: String,
	DeleteAt: String,
	UserId: mongoose.Schema.ObjectId,
	ChannelId: mongoose.Schema.ObjectId,
	PostId: mongoose.Schema.ObjectId,
	Path: String,
	ThumbnailPath: String,
	PreviewPath: String,
	Name: String,
	DisplayName: String,
	Extension: String,
	Size: String,
	MimeType: String,
	Width: Number,
	Height: Number,
	HasPreviewImage: String,
	Props: String,
	Hashtags: String
}
var fileSchema = new mongoose.Schema(filesProps);



//版本信息
var versionProps = {
	CreateAt: String
}
var versions = mongoose.model("versions", versionProps);
//建表
//团队
var teams = mongoose.model("teams", teamsSchema);
//团队成员
var teamMembers = mongoose.model("teamMembers", teammembersSchema);
//频道
var channels = mongoose.model("channels", channelsSchema);
//用户
var user = mongoose.model("users", userSchema);
//频道成员
var channelMembers = mongoose.model("channelMembers", channelMembersSchema);
//消息
var post = mongoose.model("post", postSchema);
//文件
var files = mongoose.model("files", fileSchema);

/****************************
 * 自动初始化一个team和一个channels
 * testTeams 默认teams
 * testChannels 所有人群组
 ****************************/
new Rx.Observable(observer => {
	teams.find({
		DisplayName: SERVER_CONST.DEFAULT_TEAM
	}, function (fError, fResult) {
		if (!fResult || fResult.length < 1) {
			new teams({
				DisplayName: SERVER_CONST.DEFAULT_TEAM,
				Name: SERVER_CONST.DEFAULT_TEAM,
				UpdateAt: null,
				DeleteAt: new Date().getTime(),
				Description: null,
				Email: null,
				Type: null,
				CompanyName: null,
				AllowedDomains: null,
				InviteId: null,
				AllowOpenInvite: null,
				LastTeamIconUpdate: null,
				SchemeId: null,
			}).save(function (error, result) {
				observer.next(result);
				observer.complete();
			});
		} else {
			observer.next(fResult[0]);
			observer.complete();
		}
	});
}).pipe(
	operators.mergeMap((res) => {
		return new Rx.Observable(observer => {
			channels.find({
				DisplayName: SERVER_CONST.DEFAULT_CHANNEL
			}, function (fError, fResult) {
				if (fResult.length < 1) {
					new channels({
						DisplayName: SERVER_CONST.DEFAULT_CHANNEL,
						Name: SERVER_CONST.DEFAULT_CHANNEL,
						CreateAt: new Date().getTime(),
						TeamId: res['_id'],
						UpdateAt: null,
						DeleteAt: null,
						Type: "publicGroup",
						Header: null,
						Purpose: null,
						LastPostAt: null,
						TotalMsgCount: null,
						ExtraUpdateAt: null,
						CreatorId: null,
						SchemeId: null
					}).save(function (s_error, s_result) {
						if (!s_error) {
							observer.next(s_result);
							observer.complete();
						}
					})
				} else {
					observer.next(fResult[0])
					observer.complete();
				}
			})
		});
	})
).subscribe((res) => { });



module.exports = {
	teams,
	channels,
	user,
	teamMembers,
	channelMembers,
	post,
	files,
	versions
}
